//
//  SXHomeController.m
//  Weibo1
//
//  首页
//

#import "SXHomeController.h"

#import "SXTitleBtn.h"
#import "SXPopMenu.h"
#import "SXTableController.h"
#import "SXAccount.h"
#import "AFNetworking.h"
#import "SXAccountTool.h"
#import "SXTitleMenuController.h"
#import "UIImageView+WebCache.h"
#import "SXStatus.h"
#import "SXUser.h"
#import "MJExtension.h"
#import "SXUMengController.h"
#import "UMSocial.h"
@interface SXHomeController ()<SXPopMenuDelegate, UMSocialUIDelegate>
///  微博数组
@property (nonatomic, strong) NSMutableArray *statuses;
@end
@implementation SXHomeController

- (NSMutableArray *)statuses {
    if (!_statuses) {
        _statuses = [NSMutableArray array];
    }
    return _statuses;
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    // 设置导航栏内容
    [self setupNav];
    
    // 获得用户信息（昵称）
    [self setupUserInfo];
    
    // refresh
    [self setupRefresh];
}

- (void)setupRefresh {
    
    UIRefreshControl *control = [[UIRefreshControl alloc] init];
    [control addTarget:self action:@selector(refreshStateChange:) forControlEvents:UIControlEventValueChanged];
    [self.tableView addSubview:control];
    //  一进来就刷新
    [control beginRefreshing];
    [self refreshStateChange:control];
}

- (void)refreshStateChange:(UIRefreshControl *)control {
    

    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    SXAccount *account = [SXAccountTool account];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"access_token"] = account.access_token;

    // 取出最前面的微博（最新的微博，ID最大的微博）
    SXStatus *firstStatus = [self.statuses firstObject];
    if (firstStatus) {
        // 若指定此参数，则返回ID比since_id大的微博
        params[@"since_id"] = firstStatus.idstr;
    }
    
    [mgr GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
       
        NSArray *newStatuses = [SXStatus objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        // 将最新的微博数据，添加到总数组的最前面
        NSRange range = NSMakeRange(0, newStatuses.count);
        NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:range];
        [self.statuses insertObjects:newStatuses atIndexes:set];
        // reload data
        [self.tableView reloadData];
        
        [control endRefreshing];
        // 显示最新微博数量
        [self showNewStatusCount:newStatuses.count];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        SXLog(@"请求失败-%@", error);
        [control endRefreshing];
    }];
    
}

- (void)showNewStatusCount:(int)count {
    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"timeline_new_status_background"]];
    label.width = [UIScreen mainScreen].bounds.size.width;
    label.height = 35;
    if (count == 0) {
        label.text = @"没有新的微博";
    } else {
        label.text = [NSString stringWithFormat:@"%d条新微博", count];
    }
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:16];
    label.y = 64 - label.height;
    [self.navigationController.view insertSubview:label aboveSubview:self.navigationController.navigationBar];
    CGFloat duration = 1.0;
    [UIView animateWithDuration:duration animations:^{
        label.transform = CGAffineTransformMakeTranslation(0, label.height);
    }completion:^(BOOL finished) {
        CGFloat delay = 1.0;
        [UIView animateWithDuration:delay animations:^{
            label.transform = CGAffineTransformIdentity;
        }completion:^(BOOL finished) {
            [label removeFromSuperview];
        }];
    }];
}
- (void)setupUserInfo {
    // https://api.weibo.com/2/users/show.json
    // access_token	false	string	采用OAuth授权方式为必填参数，其他授权方式不需要此参数，OAuth授权后获得。
    // uid	false	int64	需要查询的用户ID。
    
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    SXAccount *account = [SXAccountTool account];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"access_token"] = account.access_token;
    params[@"uid"] = account.uid;
    
    [mgr GET:@"https://api.weibo.com/2/users/show.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
        UIButton *titleBtn = (UIButton *)self.navigationItem.titleView;
        SXUser *user = [SXUser objectWithKeyValues: responseObject];
        [titleBtn setTitle:user.name forState:UIControlStateNormal];
        // save to sandbox
        account.name = user.name;
        [SXAccountTool saveAccount:account];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        SXLog(@"请求失败-%@", error);
    }];
}

- (void)setupNav {
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_friendsearch" highImageName:@"navigationbar_friendsearch_highlighted" target:self action:@selector(friendsearchClick)];

    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_pop" highImageName:@"navigationbar_pop_highlighted" target:self action:@selector(popClick)];
    
    [self addTitleView];
}

- (void)friendsearchClick {
    SXLog(@"friendsearchClick");
    SXUMengController *umvc = [[SXUMengController alloc] init];
    [self presentViewController:umvc animated:YES completion:nil];
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"507fcab25270157b37000010"
                                      shareText:@"你要分享的文字"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToSina,UMShareToTencent, UMShareToWechatSession,UMShareToWechatTimeline, UMShareToQzone, UMShareToQQ, UMShareToRenren, UMShareToDouban,UMShareToEmail,UMShareToSms, UMShareToFacebook, UMShareToTwitter,nil]
                                       delegate:self];
}
- (void)popClick {
    SXLog(@"popClick");
}
- (void)addTitleView {
    // 中央按钮
    SXTitleBtn *titleBtn = [[SXTitleBtn alloc] init];
    
    NSString *name = [SXAccountTool account].name;
    // 有名字就设置名字，没有就设置首页
    [titleBtn setTitle:name? name:@"首页" forState:UIControlStateNormal];
    
    self.navigationItem.titleView = titleBtn;
    [titleBtn addTarget:self action:@selector(centerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)centerBtnClick:(SXTitleBtn *)titleBtn {
    
    // 1.创建下拉菜单
    SXPopMenu *menu = [SXPopMenu menu];
    menu.delegate = self;
    
    // 2.设置内容
    SXTitleMenuController *vc = [[SXTitleMenuController alloc] init];
    vc.view.height = 150;
    vc.view.width = 150;
    menu.contentController = vc;
    
    // 3.显示
    [menu showFrom:titleBtn];
}
#pragma mark - SXPopMenuDelegate
- (void)SXPopMenuDidShow:(SXPopMenu *)menu
{
    SXTitleBtn *titleButton = (SXTitleBtn *)self.navigationItem.titleView;
    // 让箭头向上
    titleButton.selected = YES;
}

- (void)SXPopMenuDidDismissed:(SXPopMenu *)popMenu {
    
    SXTitleBtn *titleBtn = (SXTitleBtn *)self.navigationItem.titleView;
    titleBtn.selected = NO;
}
#pragma mark - UITableViewDatasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.statuses.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"homeCellID";
    UITableViewCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
    }
    SXStatus *status = self.statuses[indexPath.row];
    SXUser *user = status.user;
    cell.textLabel.text = user.name;
    cell.detailTextLabel.text = status.text;
    UIImage *placeHolder = [UIImage imageNamed:@"avatar_default_small"];
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:user.profile_image_url] placeholderImage:placeHolder];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.navigationController pushViewController:[[SXTableController alloc] init] animated:YES];
//    [self presentViewController:[[SXTableController alloc] init] animated:YES completion:nil];
}
@end
